#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Copyright (c) 2015  Data Enlighten Technology (Beijing) Co.,Ltd

from datetime import date
import logging
import logging.config
import os

__author__ = 'Neo'


def get_date_string():
    today_str = date.today().strftime("%Y_%m_%d")
    return today_str


def get_log_filename(root_dir, date_str):
    log_path = os.path.join(root_dir, 'data/mj_baselog/', date_str)
    if not os.path.exists(log_path):
        os.makedirs(log_path)

    filename = 'daily.log'
    return os.path.join(log_path, filename)


__log_level = logging.INFO


def config_log_level(level):
    global __log_level
    __log_level = logging.INFO


__loggers = {}
__root_dir = "."
__log_level = logging.INFO
__curr_date_str = ""


def _get_root_logger(app_name, root_dir, level):
    global __loggers

    today_str = get_date_string()

    __curr_date_str = today_str

    log_filename = get_log_filename(root_dir, today_str)

    logger_formatter = logging.Formatter(fmt='%(asctime)s - %(levelname)s - %(message)s',
                                         datefmt='%Y-%m-%d, %a %H:%M:%S')

    logger = logging.getLogger(app_name)

    if app_name not in __loggers:
        logger.setLevel(level)

        file_handler = logging.FileHandler(log_filename)
        file_handler.setLevel(__log_level)
        file_handler.setFormatter(logger_formatter)
        logger.addHandler(file_handler)
        __loggers[app_name] = file_handler

        console_handler = logging.StreamHandler()
        console_handler.setLevel(__log_level)
        console_handler.setFormatter(logger_formatter)
        logger.addHandler(console_handler)

    elif __curr_date_str != today_str:
        file_handler = __loggers[app_name]
        logger.removeHandler(file_handler)

        file_handler = logging.FileHandler(log_filename)
        file_handler.setLevel(level)
        file_handler.setFormatter(logger_formatter)
        logger.addHandler(file_handler)

        __loggers[app_name] = file_handler

    return logger


def get_logger(app_name, module_name, root_dir=None, level=None):
    global __root_dir
    global __log_level

    if root_dir:
        __root_dir = root_dir

    if level:
        __log_level = level

    app_logger = _get_root_logger(app_name, __root_dir, __log_level)
    if not module_name:
        return app_logger

    logger_id = "{0}.{1}".format(app_name, module_name)
    return logging.getLogger(logger_id)


DEBUG = logging.DEBUG
INFO = logging.INFO
WARNING = logging.WARNING
ERROR = logging.ERROR


if __name__ == '__main__':
    my_app_logger = get_logger("myapp", "main", ".", logging.INFO)
    my_app_logger.info("Hello world")
    my_app_logger.warning("This should appear")
